

<template>
  <div class="app-manage">
    <h2>APK包管理</h2>
    
    <!-- 上传表单 -->
    <a-card class="form-card">
      <a-form :model="appForm" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" :rules="formRules">
        <a-form-item label="应用图标" name="icon">
          <a-upload
            :custom-request="handleIconUpload"
            :before-upload="beforeIconUpload"
            :show-upload-list="false"
            class="avatar-uploader">
            <img v-if="appForm.icon" :src="appForm.icon" class="avatar" />
            <div v-else class="avatar-uploader-icon">
              <PlusOutlined />
            </div>
          </a-upload>
        </a-form-item>

        <a-form-item label="应用名称" name="name">
          <a-input v-model:value="appForm.name" placeholder="请输入应用名称" />
        </a-form-item>

        <a-form-item label="版本号" name="version">
          <a-input v-model:value="appForm.version" placeholder="格式：1.0.0" />
        </a-form-item>

        <a-form-item label="APK文件" name="apkPath">
          <a-upload
            :custom-request="handleApkUpload"
            :before-upload="beforeApkUpload"
            :max-count="1"
            accept=".apk">
            <a-button type="primary">点击上传APK</a-button>
            <div class="upload-tip">
              仅支持安卓安装包，大小不超过500MB
            </div>
          </a-upload>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="submitForm">提交发布</a-button>
          <a-button @click="resetForm">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- APK记录列表 -->
    <a-card class="list-card">
      <template #title>
        <div class="card-header">
          <span>APK记录</span>
          <!-- <a-button type="primary" @click="fetchAppList">刷新</a-button> -->
        </div>
      </template>
      <a-table :data-source="appList" :columns="columns">
         <template #bodyCell="{ column, record }">
           <template v-if="column.key === 'icon'">
             <img v-if="record.icon" :src="record.icon" class="table-icon" />
             <span v-else>-</span>
           </template>
           <template v-else-if="column.key === 'fileSize'">
             {{ formatFileSize(record.fileSize) }}
           </template>
           <template v-else-if="column.key === 'updateTime'">
             {{ formatTime(record.updateTime) }}
           </template>
         </template>
       </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import adminApi from '@/api/index'

// 表单数据
const appForm = reactive({
  icon: '',
  name: '',
  version: '',
  apkPath: '',
  fileSize: 0
})

// APK记录列表
const appList = ref([])

// 表格列配置
const columns = [
  {
    title: '应用名称',
    dataIndex: 'name',
    key: 'name',
    width: 180
  },
  {
    title: '版本号',
    dataIndex: 'version',
    key: 'version',
    width: 120
  },
  {
    title: '图标',
    dataIndex: 'icon',
    key: 'icon',
    width: 100
  },
  {
    title: '文件大小',
    dataIndex: 'fileSize',
    key: 'fileSize',
    width: 120
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    width: 180
  },
  {
    title: '下载路径',
    dataIndex: 'apkPath',
    key: 'apkPath'
  }
]

// 表单验证规则
const formRules = {
  icon: [{ required: true, message: '请上传应用图标', trigger: 'blur' }],
  name: [
    { required: true, message: '请输入应用名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度2-20个字符', trigger: 'blur' }
  ],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' },
    { pattern: /^\d+(\.\d+){2}$/, message: '版本号格式：x.x.x', trigger: 'blur' }
  ],
  apkPath: [{ required: true, message: '请上传APK文件', trigger: 'blur' }]
}

// 获取APK记录列表
const fetchAppList = async () => {
  // try {
  //   const token = localStorage.getItem('token')
  //   const response = await adminApi.admin.fetchAppList({ token })
  //   if (response.code === '0') {
  //     appList.value = response.data || []
  //   } else {
  //     ElMessage.error('获取记录失败：' + (response.msg || '未知错误'))
  //   }
  // } catch (error) {
  //   ElMessage.error('获取记录失败：' + (error.message || '网络错误'))
  // }
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return '-'
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  let fileSize = size
  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024
    index++
  }
  return fileSize.toFixed(2) + ' ' + units[index]
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

// 组件挂载时获取列表
onMounted(() => {
  fetchAppList()
})

// 图标上传前验证
const beforeIconUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    message.error('上传图标只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    message.error('上传图标大小不能超过 2MB!')
    return false
  }
  return true
}

// APK上传前验证
const beforeApkUpload = (file) => {
  const isAPK = file.name.endsWith('.apk')
  const isLt500M = file.size / 1024 / 1024 < 500

  if (!isAPK) {
    message.error('只能上传APK文件!')
    return false
  }
  if (!isLt500M) {
    message.error('APK文件大小不能超过 500MB!')
    return false
  }
  
  // 记录文件大小
  appForm.fileSize = file.size
  return true
}

// 提交表单
const submitForm = async () => {
  try {
    // 构建符合API要求的数据格式
    const token = localStorage.getItem('token')
    const submitData = {
      name: 'apk',
      data: JSON.stringify({
        name: appForm.name,
        icon: appForm.icon,
        version: appForm.version,
        updateTime: new Date().getTime(),
        apkPath: appForm.apkPath,
        fileSize: appForm.fileSize
      })
    }
    
    const response = await adminApi.admin.saveApp(submitData, token)
    
    if (response.code === "0") {
      message.success('应用发布成功')
      
      // 直接在本地添加新记录到列表顶部
      appList.value.unshift(JSON.parse(submitData.data))
      
      resetForm()
    } else {
      message.error('发布失败：' + (response.msg || '未知错误'))
    }
  } catch (error) {
    message.error('发布失败：' + (error.message || '网络错误'))
  }
}

// 重置表单
const resetForm = () => {
  appForm.icon = ''
  appForm.name = ''
  appForm.version = ''
  appForm.apkPath = ''
  appForm.fileSize = 0
}

// 图标上传处理
const handleIconUpload = async (options) => {
  const formData = new FormData()
  formData.append('file', options.file)
  formData.append('moduleName', 'icon')
  
  // // 添加token参数
  // const token = localStorage.getItem('token')
  // if (token) {
  //   formData.append('token', token)
  // }
  
  try {
    const res = await adminApi.admin.uploadImg(formData)
    if (res.code === "0") {
      appForm.icon = res.data
      message.success('图标上传成功')
      options.onSuccess(res)
    } else {
      message.error('图标上传失败：' + (res.msg || '未知错误'))
      options.onError(new Error(res.msg || '上传失败'))
    }
  } catch (error) {
    message.error('图标上传失败：' + (error.message || '网络错误'))
    options.onError(error)
  }
}

// APK上传处理
const handleApkUpload = async (options) => {
  const formData = new FormData()
  formData.append('file', options.file)
  
  // 添加token参数
  const token = localStorage.getItem('token')
  if (token) {
    formData.append('token', token)
  }
  
  try {
    const res = await adminApi.admin.uploadApk(formData)
    if (res.code === "0") {
      appForm.apkPath = res.data
      message.success('APK上传成功')
      options.onSuccess(res)
    } else {
      message.error('APK上传失败：' + (res.msg || '未知错误'))
      options.onError(new Error(res.msg || '上传失败'))
    }
  } catch (error) {
    message.error('APK上传失败：' + (error.message || '网络错误'))
    options.onError(error)
  }
}
</script>

<style scoped>
.app-manage {
  padding: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.list-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-uploader {
  width: 120px;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 12px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  background: #fafafa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #1890ff;
  background: #f0f8ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
  transform: translateY(-2px);
}

.avatar-uploader-icon {
  font-size: 24px;
  color: #bfbfbf;
  transition: color 0.3s ease;
}

.avatar-uploader:hover .avatar-uploader-icon {
  color: #1890ff;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 10px;
}

.table-icon {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
}
</style>

